const gulp = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const cssnano = require('gulp-cssnano');
const concat = require('gulp-concat');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const sass = require('gulp-sass');

// 编译并压缩js
gulp.task('convertJS', function(){
    return gulp.src([

        'app/src/**/*.js',
    ])
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(uglify())
        .pipe(gulp.dest('dist/js'))
});

// 合并并压缩css
gulp.task('convertCSS', function(){
    return gulp.src('app/css/*.css')
        .pipe(concat('style.css'))
        .pipe(cssnano())
        .pipe(rename(function(path){
            path.basename += '.min';
        }))
        .pipe(gulp.dest('dist/css'));
});

// 合并并压缩scss
gulp.task('convertSCSS', function () {
    return gulp.src('app/scss/*.scss')
        .pipe(concat('bundle.css'))
        .pipe(sass())
        .pipe(cssnano())
        .pipe(rename(function(path){
            path.basename += '.min';
        }))
        .pipe(gulp.dest('dist/css'));
});

// 拷贝文件
gulp.task('copy',  function() {
    return gulp.src('app/fonts/*')
        .pipe(gulp.dest('dist/fonts'))
});

// 监视文件变化，自动执行任务
gulp.task('watch', function(){
    gulp.watch('app/css/*.css', ['convertCSS']);
    gulp.watch('app/scss/*.scss', ['convertSCSS']);
    gulp.watch(['app/src/**/*.js', 'app/src/*.js'], ['convertJS', 'browserify']);
});

// browserify
gulp.task("browserify", function () {
    setTimeout(() => {
        const b = browserify({
            entries: "dist/js/main.js"
        });

        return b.bundle()
            .pipe(source("bundle.js"))
            .pipe(gulp.dest("dist/js"));
    }, 2000);
});

gulp.task('start', ['convertJS', 'convertCSS', 'browserify', 'watch', 'convertSCSS','copy']);